package com.fengye.serialization;

import com.fengye.serialization.common.SerializeType;
import com.fengye.serialization.engine.SerializerEngine;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @Author fengye
 * @Date 2023/2/12 11:43
 **/
public class NettyDecodeHandler extends ByteToMessageDecoder {

    /** 解码对象Class */
    private Class<?> genericClass;

    /** 解码对象编码所使用序列化类型 */
    private SerializeType serializeType;

    public NettyDecodeHandler(Class<?> genericClass, SerializeType serializeType) {
        this.genericClass = genericClass;
        this.serializeType = serializeType;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        // 获取消息头所标识的消息体字节数组长度
        if(in.readableBytes() < 4) {
            return;
        }

        in.markReaderIndex();
        int dataLength = in.readInt();
        if(dataLength < 0) {
            channelHandlerContext.close();
        }

        // 若当前可以获取到的字节数小于实际长度，则直接返回，直到当前可以获取到的字节数等于实际长度
        if(in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }

        byte[] data = new byte[dataLength];
        in.readBytes(data);

        // 将字节数组反序列化为java对象
        Object obj = SerializerEngine.deserialize(data, genericClass, serializeType.getSerializeType());
        out.add(obj);
    }
}
